<template>
  <div class="register-page">
    <div class="logo">
      <img src="../assets/img/index/logo.png" alt="">
      <h1>锐智CloudSync</h1>
    </div>
    <div class="mod-new-reg-text">
      <h1>用科技</h1>
      <p>让复杂的世界更简单</p>
    </div>
    <div class="register-form">
      <h3>欢迎注册</h3>
      <p class="gray-text">已有账号？<a href="index" style="color:#2e58ff;">登录</a></p>

      <div class="form-item">
        <div class="form-group">
          <label for="username">用户名</label>
          <input type="text" id="username" v-model="username" placeholder="请设置用户名" @focus="showUsernameError = false"
            @blur="validateUsername">
        </div>
        <p v-if="showUsernameError" class="formError">
          账号不正确，仅支持中英文、数字且不能为纯数字
        </p>
      </div>

      <div class="form-item">
        <div class="form-group">
          <label for="phone">手机号</label>
          <input type="text" id="phone" v-model="phone" placeholder="可用于登录和找回密码" @focus="showPhoneError = false"
            @blur="validatePhone">
        </div>
        <p v-if="showPhoneError" class="formError">
          手机号格式不正确
        </p>
      </div>

      <div class="form-item">
        <div class="form-group">
          <label for="password">密码</label>
          <el-input type="password" id="password" v-model="password" placeholder="请设置登录密码" class="custom-input"
            style="height: 38px; width: 95%; margin-left: 5px;" show-password @focus="showPasswordError = false"
            @blur="validatePassword" />
        </div>
        <p v-if="showPasswordError" class="formError">
          密码为8~14个字符，需包含字母和数字，不允许有空格和中文
        </p>
      </div>

      <div class="form-item captcha-item">
        <label for="captcha">验证码</label>
        <input type="text" v-model="captcha" placeholder="请输入验证码">
        <button class="captcha-btn" @click="getCaptcha">获取验证码</button>
      </div>

      <button class="register-btn" :class="{ active: isFormComplete }" @click="register" :disabled="!isFormComplete">
        注册
      </button>
      

      <div class="agreement">
        <input type="checkbox" id="agree" v-model="agreed">
        <label for="agree">
          阅读并接受 :
          <a href="#">《锐智CloudSync用户协议》</a>、
          <a href="#">《儿童个人信息保护声明》</a>及
          <a href="#">《锐智CloudSync隐私权保护声明》</a>
        </label>
      </div>
    </div>
  </div>
  <button @click="Go">go</button>
</template>

<script>
import axios from 'axios';
import { useRouter } from 'vue-router';
const router = useRouter()
// 设置 axios 默认的 baseURL
axios.defaults.baseURL = 'http://127.0.0.1:8100/api';

export default {
  data() {
    return {
      username: '',
      showUsernameError: false,
      showPhoneError: false,
      showPasswordError: false,
      phone: '',
      password: '',
      captcha: '',
      agreed: false,
      isFormComplete: false // 初始化isFormComplete
    };
  },
  watch: {
    username: 'checkFormCompletion',
    phone: 'checkFormCompletion',
    password: 'checkFormCompletion',
    captcha: 'checkFormCompletion',
    agreed: 'checkFormCompletion'
  },
  methods: {
    async getCaptcha() {
      try {
        const response = await axios.get('/sendCode', {
          params: {
            phoneNumber: this.phone
          }
        });
        if (response.data.success) {
          alert('验证码已发送');
        } else {
          alert(response.data.message || '发送验证码失败，请重试');
        }
      } catch (error) {
        console.error('发送验证码请求失败:', error);
        alert('发送验证码请求失败，请稍后再试');
      }
    },
    async register() {
      if (!this.agreed) {
        alert('请先同意协议');
        return;
      }

      try {
        const response = await axios.post('/regUser', {
          username: this.username,
          phoneNumber: this.phone,
          password: this.password,
          code: this.captcha // 传入验证码
        });

        // 处理响应
        if (response.data.success) {
          alert('注册成功');
          router.push(`/index`)
        } else {
          alert(response.data.message || '注册失败，请重试');
        }
      } catch (error) {
        console.error('注册请求失败:', error);
        alert('注册请求失败，请稍后再试');
      }
    },
    checkFormCompletion() {
      // 检查是否所有字段都已填写且复选框已勾选
      this.isFormComplete =
        this.username &&
        this.phone &&
        this.password &&
        this.captcha &&
        this.agreed;
    },
    validateUsername() {
      // 验证用户名规则（中英文、数字，且不能为纯数字）
      const usernameRegex = /^(?!\d+$)[a-zA-Z0-9\u4e00-\u9fa5]+$/;
      this.showUsernameError = !usernameRegex.test(this.username);
    },
    validatePhone() {
      // 验证手机号格式
      const phoneRegex = /^1[3-9]\d{9}$/;
      this.showPhoneError = !phoneRegex.test(this.phone);
    },
    validatePassword() {
      // 验证密码格式（8-14个字符，不包含空格和中文）
      const passwordRegex = /^(?!.*\s)(?!.*[\u4e00-\u9fa5])(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{8,14}$/;
      this.showPasswordError = !passwordRegex.test(this.password);
    }
  }
};


</script>

<style scoped>
@import "../assets/css/reg.css";
</style>
